package cn.mrlong.base.view

import android.content.Context
import android.content.res.Resources
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Observer
import cn.mrlong.base.bean.MessageType
import cn.mrlong.base.utils.*
import com.afollestad.materialdialogs.MaterialDialog
import cn.mrlong.base.utils.ActivityManager
import cn.mrlong.base.utils.SharedPreferencesUtils
import cn.mrlong.base.utils.StaticConstUtils
import cn.mrlong.base.utils.ToastUtil
import cn.mrlong.base.utils.LoadingObserver
import cn.mrlong.base.utils.SnackbarUtils
import com.alibaba.android.arouter.launcher.ARouter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch


open abstract class BaseActivity<T : ViewDataBinding>() : AppCompatActivity() {
    abstract val layoutId: Int
    lateinit var binding: T
    var firstTime: Long = 0//第一次按下返回键的时间
    var secondTime: Long = 0//第二次按下返回键的时间
    var doubleKeyExit: Boolean = false//是否双击退出应用

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ActivityManager.get().push(this)
        binding = DataBindingUtil.setContentView(this, layoutId)
        binding.lifecycleOwner = this

        ARouter.getInstance().inject(this);
    }

    fun showToast(message: String) {
        ToastUtil.show(this.applicationContext, message)
    }

    override fun onDestroy() {
        super.onDestroy()
        ActivityManager.get().remove(this)
    }


    /**
     *
     * @param vm BaseViewModel
     * @param toastViewRoot View?
     */
    fun initMessage(vm: BaseViewModel, toastViewRoot: View?) {
        //通知
        vm.noticeMessage.observe(this, Observer {
            it.run {
                GlobalScope.launch(Dispatchers.Main) {
                    if (MessageType.TOAST == it.title) {
                        if (null == toastViewRoot) {
                            throw RuntimeException("Snackbar must has root view ")
                        }
                        SnackbarUtils.show(toastViewRoot, it.content.toString())
                    } else if (MessageType.DIALOG == it.title) {
                        MaterialDialog(this@BaseActivity)
                            .show {
                                title(text = "提示")
                                message(text = it.content.toString())
                                positiveButton(text = "确定")
                            }
                    }
                }
            }
        })
        vm.progressBarState.observe(
            this,
            LoadingObserver(this@BaseActivity, "加载中...")
        )
    }

    /**
     * 双击退出应用
     * @param keyCode Int
     * @param event KeyEvent
     * @return Boolean
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && doubleKeyExit) {
            if (0L == firstTime) {
                firstTime = System.currentTimeMillis()
                showToast("再次点击返回键退出应用")
            } else {
                secondTime = System.currentTimeMillis()
                val interval = secondTime - firstTime
                if (interval <= StaticConstUtils.DOUBLE_CLICK_EXIT_DENY) {
                    ActivityManager.get().finishAllActivity()
                } else {
                    firstTime = 0
                    secondTime = 0
                }
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    /**
     * api>24重写字体缩放
     * @param newBase Context
     */
    override fun attachBaseContext(newBase: Context?) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            val config = newBase?.resources?.configuration
            config?.fontScale = SharedPreferencesUtils.getFloat(
                this,
                StaticConstUtils.FONT_SIZE_FILE,
                StaticConstUtils.FONT_SIZE_VALUE_SP,
                StaticConstUtils.FONT_SIZE_VALUE
            ) //设置正常字体大小的倍数
            if (config != null) {
                val newContext = newBase.createConfigurationContext(config)
                super.attachBaseContext(newContext)
                return
            }
        }
        super.attachBaseContext(newBase)
    }

    /**
     * api<=24 重写字体缩放
     * @return Resources
     */
    override fun getResources(): Resources {
        val res = super.getResources()
        val config = res.configuration
        config.fontScale = SharedPreferencesUtils.getFloat(
            this,
            StaticConstUtils.FONT_SIZE_FILE,
            StaticConstUtils.FONT_SIZE_VALUE_SP,
            StaticConstUtils.FONT_SIZE_VALUE
        );//设置正常字体大小的倍数
        res.updateConfiguration(config, res.displayMetrics)

        return res
    }
}
